package com.ashlikun.glideutils

import android.content.Context
import com.ashlikun.glideutils.okhttp.OkHttpUrlLoader
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import com.bumptech.glide.request.RequestOptions
import java.io.InputStream

/**
 * 作者　　: 李坤
 * 创建时间: 2017/12/29　17:42
 * 邮箱　　：496546144@qq.com
 *
 *
 * 功能介绍：GlideModule
 */
@GlideModule
class MyAppGlideModule : AppGlideModule() {
    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        try {
            registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory())
        } catch (e: NoClassDefFoundError) {
            e.printStackTrace()
        }
    }

    /**
     * 是否读取清单文件配置，4.0后就不需要了
     *
     * @return
     */
    override fun isManifestParsingEnabled(): Boolean {
        return false
    }

    override fun applyOptions(context: Context, builder: GlideBuilder) {
        super.applyOptions(context, builder)
        if (GlideUtils.diskLruCacheFactory == null) {
            GlideUtils.diskLruCacheFactory = InternalCacheDiskCacheFactory(context)
        }
        builder.setDiskCache(GlideUtils.diskLruCacheFactory)
//        builder.setMemoryCache(LruResourceCach())
        val options = RequestOptions()
        options.error(GlideUtils.errorRes)
        options.placeholder(GlideUtils.placeholderRes)
        options.sizeMultiplier(0.8f)
        options.format(DecodeFormat.PREFER_RGB_565)
        options.diskCacheStrategy(DiskCacheStrategy.ALL)
        GlideUtils.initApplyOptions?.invoke(builder, options)
        builder.setDefaultRequestOptions(options)

    }
}